<template>
  <div class="settings-container">
    <h1 class="page-title">系统设置</h1>
    
    <!-- 基本设置区域 -->
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>基本设置</span>
        </div>
      </template>
      
      <el-form :model="basicSettings" label-width="120px">
        <el-form-item label="界面语言">
          <el-select v-model="basicSettings.language" placeholder="请选择语言">
            <el-option label="简体中文" value="zh-CN"></el-option>
            <el-option label="English" value="en-US"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="主题风格">
          <el-select v-model="basicSettings.theme" placeholder="请选择主题">
            <el-option label="浅色主题" value="light"></el-option>
            <el-option label="深色主题" value="dark"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="日期格式">
          <el-select v-model="basicSettings.dateFormat" placeholder="请选择日期格式">
            <el-option label="YYYY-MM-DD" value="YYYY-MM-DD"></el-option>
            <el-option label="DD/MM/YYYY" value="DD/MM/YYYY"></el-option>
            <el-option label="MM/DD/YYYY" value="MM/DD/YYYY"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 通知设置区域 -->
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>通知设置</span>
        </div>
      </template>
      
      <el-form :model="notificationSettings" label-width="120px">
        <el-form-item label="系统通知">
          <el-switch v-model="notificationSettings.systemNotification" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
        
        <el-form-item label="邮件通知">
          <el-switch v-model="notificationSettings.emailNotification" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
        
        <el-form-item label="操作提醒">
          <el-switch v-model="notificationSettings.operationAlert" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
        
        <el-form-item label="登录提醒">
          <el-switch v-model="notificationSettings.loginAlert" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 安全设置区域 -->
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>安全设置</span>
        </div>
      </template>
      
      <el-form label-width="120px">
        <el-form-item>
          <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
        </el-form-item>
        
        <el-form-item label="登录保护">
          <el-switch v-model="securitySettings.loginProtection" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
        
        <el-form-item>
          <el-button @click="handleViewLoginRecords">查看登录记录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 保存按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleSave">保存设置</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>
    
    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="80px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitPassword">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 登录记录对话框 -->
    <el-dialog v-model="loginRecordsDialogVisible" title="登录记录" width="800px">
      <el-table :data="loginRecords" style="width: 100%" max-height="400">
        <el-table-column prop="time" label="登录时间" width="180"></el-table-column>
        <el-table-column prop="ip" label="IP地址" width="150"></el-table-column>
        <el-table-column prop="location" label="登录地点" width="200"></el-table-column>
        <el-table-column prop="device" label="设备信息"></el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'success' ? 'success' : 'danger'">
              {{ scope.row.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="loginRecordsDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { 
  ElMessage, 
  ElMessageBox,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElCard,
  ElButton,
  ElSwitch,
  ElDialog,
  ElTable,
  ElTableColumn,
  ElTag
} from 'element-plus'

// 基本设置数据
const basicSettings = reactive({
  language: 'zh-CN',
  theme: 'light',
  dateFormat: 'YYYY-MM-DD'
})

// 通知设置数据
const notificationSettings = reactive({
  systemNotification: true,
  emailNotification: false,
  operationAlert: true,
  loginAlert: true
})

// 安全设置数据
const securitySettings = reactive({
  loginProtection: false
})

// 修改密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单引用
const passwordFormRef = ref(null)

// 对话框显示状态
const passwordDialogVisible = ref(false)
const loginRecordsDialogVisible = ref(false)

// 登录记录数据（模拟）
const loginRecords = ref([
  {
    id: 1,
    time: '2024-01-01 10:00:00',
    ip: '192.168.1.1',
    location: '中国北京',
    device: 'Chrome / Windows 10',
    status: 'success'
  },
  {
    id: 2,
    time: '2023-12-31 16:30:00',
    ip: '192.168.1.2',
    location: '中国上海',
    device: 'Firefox / macOS',
    status: 'success'
  },
  {
    id: 3,
    time: '2023-12-30 09:15:00',
    ip: '10.0.0.1',
    location: '内网',
    device: 'Safari / iOS',
    status: 'success'
  }
])

// 修改密码表单验证规则
const passwordRules = {
  oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 打开修改密码对话框
const handleChangePassword = () => {
  passwordDialogVisible.value = true
}

// 提交修改密码
const handleSubmitPassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    // 这里应该调用API修改密码
    console.log('修改密码:', passwordForm)
    
    // 模拟成功
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
    
    // 重置表单
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error) {
    console.error('密码修改失败:', error)
  }
}

// 查看登录记录
const handleViewLoginRecords = () => {
  loginRecordsDialogVisible.value = true
}

// 保存设置
const handleSave = () => {
  // 合并所有设置
  const allSettings = {
    basic: { ...basicSettings },
    notification: { ...notificationSettings },
    security: { ...securitySettings }
  }
  
  // 这里应该调用API保存设置
  console.log('保存设置:', allSettings)
  
  // 保存到本地存储
  localStorage.setItem('userSettings', JSON.stringify(allSettings))
  
  ElMessage.success('设置保存成功')
}

// 重置设置
const handleReset = () => {
  ElMessageBox.confirm('确定要重置所有设置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 重置为默认值
    Object.assign(basicSettings, {
      language: 'zh-CN',
      theme: 'light',
      dateFormat: 'YYYY-MM-DD'
    })
    
    Object.assign(notificationSettings, {
      systemNotification: true,
      emailNotification: false,
      operationAlert: true,
      loginAlert: true
    })
    
    Object.assign(securitySettings, {
      loginProtection: false
    })
    
    ElMessage.success('设置已重置')
  }).catch(() => {
    // 用户取消重置
  })
}

// 加载设置
const loadSettings = () => {
  try {
    const savedSettings = localStorage.getItem('userSettings')
    if (savedSettings) {
      const settings = JSON.parse(savedSettings)
      if (settings.basic) Object.assign(basicSettings, settings.basic)
      if (settings.notification) Object.assign(notificationSettings, settings.notification)
      if (settings.security) Object.assign(securitySettings, settings.security)
    }
  } catch (error) {
    console.error('加载设置失败:', error)
  }
}

// 初始化加载设置
loadSettings()
</script>

<style scoped>
.settings-container {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: bold;
  font-size: 16px;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}

.action-buttons .el-button {
  margin: 0 10px;
}
</style>